/* eslint-disable no-console */
<template>
  <div id="app">
    <p style="color:red;font-size:2em;">扫码内容：{{scanMsg}}</p>
    <!-- <input
      type="button"
      value="函数防抖"
      @click="debounce"
    > -->
    <a href="kdpda://kdpda.kingdee.com">打开扫码工具</a>
    <p>
      下载扫码工具：<a href="http://"></a>
    </p>
  </div>
</template>

<script>
import VConsole from 'vconsole'
export default {
  name: "app",
  data() {
    return {
      count: 0,
      scanMsg: '没有内容', // 扫码内容
      mySocket: WebSocket // 用于跟扫码工具通信（ws://127.0.0.1:5555/scan）
    };
  },
  components: { },
  beforeCreate() {
    const vConsole = new VConsole()
    // vConsole.$dom.offsetTop = 0;
    // vConsole.$dom.offsetLeft = 0;
    vConsole.show();
    // eslint-disable-next-line no-console
    console.log("beforeCreate");
  },
  /*
  0 ：对应常量CONNECTING (numeric value 0)，
正在建立连接连接，还没有完成。The connection has not yet been established.
1 ：对应常量OPEN (numeric value 1)，
连接成功建立，可以进行通信。The WebSocket connection is established and communication is possible.
2 ：对应常量CLOSING (numeric value 2)
连接正在进行关闭握手，即将关闭。The connection is going through the closing handshake.
3 : 对应常量CLOSED (numeric value 3)
连接已经关闭或者根本没有建立。The connection has been closed or could not be opened.
  */
  created() {
    // 页面创建到缓存只是调用一次
    // 监听H5页面激活或失效
    document.addEventListener("visibilitychange", () => {
      const date = new Date();
      if (document.hidden) {
        // 页面被挂起
        this.$debounce(() => {
          // eslint-disable-next-line no-console
          console.log(
            "hidden",
            date.getSeconds() + "---" + date.getMilliseconds()
          );
          if (this.mySocket.readyState !== 1) {
            this.over(); // 关闭socket
          }
        }, 2000)();
      } else {
        // 页面呼出
        this.$debounce(() => {
          // eslint-disable-next-line no-console
          console.log(
            "shown",
            date.getSeconds() + "---" + date.getMilliseconds()
          );
          if (this.mySocket.readyState !== 1) {
            this.buildWebSocket(); // 重新建立socket
          }
        }, 2000)();
      }
    });
    // socket.close()
    this.over = () => {
      if(this.mySocket){
        this.mySocket.close();
      }
    };
    // eslint-disable-next-line no-console
    console.log("created");
  },
  beforeMount() {
    // eslint-disable-next-line no-console
    console.log("beforeMount");
  },
  mounted() {
    this.buildWebSocket(this.handleScanCode);
    // 测试，2分钟刷新页面一次，看看websocket会不会断开
    setInterval(() => {
      // location.reload();
      console.log('*******定时2秒访问：'+new Date() + ", socket state = " + this.mySocket.readyState)
      if (this.mySocket.readyState !== 1){
         console.error('链接websocket异常，状态：' + this.mySocket.readyState)
         this.buildWebSocket(this.handleScanCode);// 重连websocket
        return;
      }
      this.mySocket.send("我每两秒钟刷新一次，时间: "+new Date().toDateString()+"--"+new Date().toLocaleTimeString())
    }, 2000);
    // ping pong
    setInterval(() => {
      var ping = {"type":"ping"};
      this.mySocket.ping(JSON.stringify(ping));
    }, 60* 1000);
    // eslint-disable-next-line no-console
    console.log("mounted");
  },
  beforeUpdate() {
    // eslint-disable-next-line no-console
    console.log("beforeUpdate");
  },
  updated() {
    // eslint-disable-next-line no-console
    console.log("updated");
  },
  activated() {
    // eslint-disable-next-line no-console
    console.log("activated");
  },
  deactivated() {
    // eslint-disable-next-line no-console
    console.log("deactivated");
  },
  beforeDestroy() {
    // eslint-disable-next-line no-console
    console.log("beforeDestroy");
  },
  destroyed() {
    // eslint-disable-next-line no-console
    console.log("destroyed");
  },
  methods: {
    counting() {
      // eslint-disable-next-line no-console
      console.log(this.count);
      this.count++;
    },
    debounce() {
      // eslint-disable-next-line no-console
      //console.log('click me',this.lodashUtils);
      // eslint-disable-next-line no-console
      //const newArr = this.lodashUtils.concat([1,2,3],[2,4],2,5);
      // eslint-disable-next-line no-console
      //console.log(newArr);
      this.$debounce(this.counting, 2000)();
    },
    /* 处理扫码内容 */
    handleScanCode(scanData) {
      // eslint-disable-next-line no-console
      console.log("得到信息：", scanData);
      this.scanMsg = scanData;
    },
    /* 建立socket连接 */
    buildWebSocket(increateCallback) {
      let callback = this.handleScanCode; // 设置扫码处理函数
      if (typeof increateCallback === "function") {
        callback = increateCallback; // 支持单独配置socket
      }
      var vm = this;
      vm.mySocket = new WebSocket("ws://127.0.0.1:5555/scan");
      // eslint-disable-next-line no-unused-vars
      vm.mySocket.onopen = function(event) {
        // 发送一个初始化消息
        vm.mySocket.send("你好，我是客户端发送到测试消息");
        // 监听消息
        vm.mySocket.onmessage = function(event) {
          // eslint-disable-next-line no-console
          console.log(event.data);
          // eslint-disable-next-line no-undef
          callback(event.data);
        };
        // 监听Socket的关闭
        vm.mySocket.onclose = function(event) {
          // eslint-disable-next-line no-console
          console.log("Client notified socket has closed", event);
        };
      };
      vm.mySocket.onerror = function(event) {
        // eslint-disable-next-line no-console
        console.log(
          "Client error： socket state = " + vm.mySocket.readyState,
          event
        );
      };
    }
  }
};
</script>

<style>
#app {
  font-family: "Avenir", Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>
